package com.sanpu.kxe.business.main.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sanpu.library.imagechoose.PhotoPreview;
import com.sanpu.kxe.business.main.bean.CertificationOldOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.contract.OldAuthThirdStepContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.business.main.view.MainActivity;
import com.sanpu.kxe.business.main.view.OldCertificateSecondActivity;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.module.luban.Luban;
import com.sanpu.kxe.module.luban.OnRenameListener;
import com.sanpu.kxe.utils.AppContextUtil;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：认证人工审核第三步
 * Created by 薛勇军 on 2019/5/15.
 */

public class OldAuthThirdStepPresenter implements OldAuthThirdStepContract.Presenter {

    private OldAuthThirdStepContract.View mView;

    private HashMap<String, File> imgFiles;

    private CertificationOldOutput mOutput;

    private CompositeSubscription mSubscription;

    public OldAuthThirdStepPresenter(OldAuthThirdStepContract.View mView,
                                  HashMap<String, File> mUploadFiles, CertificationOldOutput mOutput) {
        this.mView = mView;
        if (mUploadFiles != null && !mUploadFiles.isEmpty()) {
            imgFiles = mUploadFiles;
        } else {
            imgFiles = new HashMap<>();
        }
        this.mOutput = mOutput;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void onCommitData() {
        if (imgFiles.size() < 5) {
            ToastUtil.showTextViewPrompt("缺少有效的证件照");
            return;
        }
        mView.showLoadingDialog(false, "证件认证信息上传中...");
        Subscription subscription = MainModel.getInstance().realNamePicAuth(mOutput, imgFiles)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        UserCenterOutput userCenterOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
                        if (userCenterOutput != null) {
                            userCenterOutput.setChkSts(CommonConfig.AUTHEN_AUDIT);
                        }
                        CacheManage.getInstance().saveCache(CacheModel.USER_CENTER_KEY, userCenterOutput);
                        GlobalDialog dialog = new GlobalDialog(mView.getContext())
                                .content("恭喜你完成实名认证，请耐心等待审核！");
                        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                AppContextUtil.finishAllExclByActivity(MainActivity.class.getName());
                            }
                        });
                        dialog.show();
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void takePhoto(String photo, int code) {
        ArrayList<String> photoPaths = new ArrayList<>();
        photoPaths.add(photo);
        PhotoPreview.builder()
                .setPhotos(photoPaths)
                .setCurrentItem(0)
                .start((Activity) mView.getContext(), code);
    }

    @Override
    public void onCompress(String filePath, final String reName) {
        try {
            final OldCertificateSecondActivity activity = (OldCertificateSecondActivity) mView.getContext();
            activity.showLoadingDialog(false, "照片压缩处理中...");
            //同步方法请尽量避免在主线程调用以免阻塞主线程
            Observable.just(filePath)
                    .observeOn(Schedulers.io())
                    .map(new Func1<String, List<File>>() {
                        @Override
                        public List<File> call(String filePath) {
                            return luban(filePath, reName);
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<File>>() {
                        @Override
                        public void onCompleted() {
                            activity.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            activity.dismissLoadingDialog();
                        }

                        @Override
                        public void onNext(List<File> files) {
                            if (files != null && files.size() > 0) {
                                imgFiles.put(reName, files.get(0));
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * luban图片压缩
     *
     * @param filePath 图片地址
     * @param reName   重命名
     * @return
     */
    private List<File> luban(String filePath, final String reName) {
        try {
            // 同步方法直接返回压缩后的文件
            return Luban.with(mView.getContext())
                    .load(filePath)
                    .ignoreBy(CommonConfig.LUBAN_COMPRESSSIZE)
                    .isNeedDesired(true)
                    .desiredValue(CommonConfig.LUBAN_COMPRESSSIZE)
                    .setRenameListener(new OnRenameListener() {
                        @Override
                        public String rename(String filePath) {
                            return reName + "_" + System.currentTimeMillis();
                        }
                    })
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取网络图片文件
     */
    @Override
    public void getImageFileByNet(String imageUrl, final String fileName) {
        Glide.with(mView.getContext())
                .load(imageUrl)//强制Glide返回一个Bitmap对象
                .asBitmap()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        if (bitmap != null) {
                            String filePath = FileUtil.compressAndSave(bitmap, fileName);
                            File imageFile = null;
                            if (!TextUtils.isEmpty(filePath)) {
                                imageFile = new File(filePath);
                            }
                            if (imageFile != null && imageFile.exists()) {
                                if (imgFiles == null) {
                                    imgFiles = new HashMap<>();
                                }
                                imgFiles.put(fileName, imageFile);
                            }
                            if (imgFiles.size() == 5) {
                                mView.dismissLoadingDialog();
                            }
                        }
                    }
                });
    }

    @Override
    public void removeFile(String fileKey) {
        if (imgFiles != null && imgFiles.containsKey(fileKey)) {
            imgFiles.remove(fileKey);
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
